<template>
  <div v-if="showValue" class="c-date-picker-wrapper">
    <div class="date-picker-with-mark">
      <el-popover
        placement="top-start"
        title="上手值"
        effect="dark"
        :width="200"
        trigger="hover"
        :disabled="!showOldValue"
        :content="oldValue ? oldValue : '无'"
      >
        <template #reference>
          <el-date-picker
            v-model="dateValue"
            :type="type as any"
            :format="format"
            :placeholder="placeholder"
            :disabled="disabled || isLoading"
            :clearable="clearable"
            :readonly="readonly"
            :size="size as any"
            :editable="editable"
            :unlink-panels="unlinkPanels"
            :range-separator="rangeSeparator"
            :start-placeholder="startPlaceholder"
            :end-placeholder="endPlaceholder"
            :class="{ 'show-red': oldValue != formatDateValue(dateValue) && showOldValue }"
            v-bind="$attrs"
            @change="handleChange"
            @blur="handleBlur"
            @focus="handleFocus"
            @clear="handleClear"
          />
        </template>
      </el-popover>
      <div v-if="showRequiredMark && !hideRequiredMark" class="required-mark">*</div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElDatePicker } from 'element-plus'

/**
 * DatePicker 二次封装，增强了以下功能：
 * 1. 加载状态管理
 * 2. 可配置的required标记
 * 3. 统一的事件处理
 * 4. 显示上手值
 * 5. 是否变红逻辑
 */
const props = defineProps({
  // 绑定值
  modelValue: {
    type: [String, Date, Array],
    default: '',
  },
  // 日期选择器类型
  type: {
    type: String,
    default: 'date',
    validator: (value: string) => {
      return ['year', 'month', 'date', 'dates', 'datetime', 'datetimerange', 'daterange'].includes(
        value,
      )
    },
  },
  // 占位符
  placeholder: {
    type: String,
    default: '',
  },
  // 开始日期占位符
  startPlaceholder: {
    type: String,
    default: '',
  },
  // 结束日期占位符
  endPlaceholder: {
    type: String,
    default: '',
  },
  // 格式化字符串
  format: {
    type: String,
    default: 'YYYY-MM-DD',
  },
  // 范围选择时的分隔符
  rangeSeparator: {
    type: String,
    default: '至',
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 是否可清空
  clearable: {
    type: Boolean,
    default: true,
  },
  // 是否显示加载状态
  loading: {
    type: Boolean,
    default: false,
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false,
  },
  // 输入框尺寸
  size: {
    type: String,
    default: 'default',
    validator: (value: string) => {
      return ['large', 'default', 'small', 'mini'].includes(value)
    },
  },
  // 文本框是否可输入
  editable: {
    type: Boolean,
    default: true,
  },
  // 在范围选择器中取消两个日期面板之间的联动
  unlinkPanels: {
    type: Boolean,
    default: false,
  },
  // 是否显示必填标记
  showRequiredMark: {
    type: Boolean,
    default: false,
  },
  // 是否隐藏必填标记（优先级高于showRequiredMark）
  hideRequiredMark: {
    type: Boolean,
    default: false,
  },
  // 是否显示
  showValue: {
    type: Boolean,
    default: true,
  },
  // 是否显示上手值
  showOldValue: {
    type: Boolean,
    default: false,
  },
  // 上手值
  oldValue: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue', 'change', 'clear', 'focus', 'blur'])

// 内部日期值 - 使用Element Plus兼容的类型定义
const dateValue = ref<any>(props.modelValue)
// 内部加载状态
const isLoading = ref(props.loading)

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    dateValue.value = newVal
  },
  { deep: true },
)

// 监听外部loading状态变化
watch(
  () => props.loading,
  (newVal) => {
    isLoading.value = newVal
  },
)

// 格式化日期值为字符串，用于与oldValue比较
const formatDateValue = (value: any): string => {
  if (!value) {
    return ''
  }

  if (Array.isArray(value)) {
    // 处理日期范围
    return value.join(props.rangeSeparator)
  } else if (value instanceof Date) {
    // 处理Date对象
    return value.toISOString().split('T')[0]
  } else {
    // 处理字符串
    return String(value)
  }
}

// 处理日期变化事件
const handleChange = (value: any) => {
  dateValue.value = value
  emit('update:modelValue', value)
  emit('change', value)
}

// 处理清除事件
const handleClear = () => {
  dateValue.value = props.type.includes('range') ? [] : ''
  emit('update:modelValue', dateValue.value)
  emit('clear')
}

// 处理聚焦事件
const handleFocus = (event: FocusEvent) => {
  emit('focus', event)
}

// 处理失焦事件
const handleBlur = (event: FocusEvent) => {
  emit('blur', event)
}
</script>

<style lang="scss" scoped>
.c-date-picker-wrapper {
  display: inline-block;
  width: 100%;
}

.date-picker-with-mark {
  position: relative;
  display: inline-flex;
  align-items: center;
}

.required-mark {
  margin-left: 2px;
  color: #f56c6c;
  font-size: 14px;
  line-height: 1;
}

/* 日期值与上手值不同时的变红样式 */
:deep(.show-red) .el-input__inner {
  color: red;
}
</style>
